package cc.higou.service;

import cc.higou.core.dao.ColorMapper;
import cc.higou.core.dao.ProductMapper;
import cc.higou.core.dao.SkuMapper;
import cc.higou.core.pojo.Color;
import cc.higou.core.pojo.Product;
import cc.higou.core.pojo.Sku;
import cc.higou.core.pojo.SuperPojo;
import cc.higou.core.tools.PageHelper;
import com.github.abel533.entity.Example;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 说明：
 * 商品信息的业务层的实现类
 *
 * @author:dongxing
 * @time:--
 */

@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private Jedis jedis;

    @Autowired
    private SolrServer solrServer;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    public PageHelper.Page<Product> findByExample(Product product, Integer pageNum, Integer pageSize) {
        //分页查询
        PageHelper.startPage(pageNum, pageSize);
        if (product.getName() == null) {
            product.setName("");
        }
        Example example = new Example(Product.class);

        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("name", "%" + product.getName() + "%");
        if (product.getBrandId() != null) {
            criteria.andEqualTo("brandId", product.getBrandId());
        }
        if (product.getIsShow() != null) {
            criteria.andEqualTo("isShow", product.getIsShow());
        }
        //id降序排序
        example.setOrderByClause("id desc");
        productMapper.selectByExample(example);
        PageHelper.Page endPage = PageHelper.endPage();
        return endPage;
    }

    @Override
    public List<Color> findEnableColors() {
        Example example = new Example(Color.class);
        example.createCriteria().andNotEqualTo("parentId", 0 + "");
        List<Color> colors = colorMapper.selectByExample(example);
        return colors;
    }

    @Override
    public void deleteById(String id) {
        Long aLong = new Long(id);
        //删除对应的库存表
        Sku sku = new Sku();
        sku.setProductId(aLong);
        skuMapper.delete(sku);
        productMapper.deleteByPrimaryKey(aLong);
    }

    @Override
    public void add(Product product) {
        product.setIsShow(0);
        product.setIsDel(1);
        product.setCreateTime(new Date());
        //保存商品
        Long pno = jedis.incr("pno");
        product.setId(pno);
        productMapper.insert(product);
        //保存库存表
        //获取尺码表
        String[] sizes = product.getSizes().split(",");
        //获取颜色表
        String[] colors = product.getColors().split(",");
        for (String size : sizes) {
            for (String color : colors) {
                Sku sku = new Sku();
                sku.setProductId(pno);
                sku.setColorId(Long.parseLong(color));
                sku.setSize(size);
                //设置数据
                sku.setMarketPrice(1000f);
                sku.setPrice(2000f);
                sku.setDeliveFee(10f);
                sku.setStock(222);
                sku.setUpperLimit(200);
                sku.setCreateTime(new Date());
                skuMapper.insert(sku);
            }
        }
    }

    @Override
    public void update(Product product, final String ids) throws IOException, SolrServerException {
        String[] split = ids.split(",");
        List list = new ArrayList<>();
        for (String id : split) {
            list.add(id);
        }
        Example example = new Example(Product.class);
        example.createCriteria().andIn("id", list);
        productMapper.updateByExampleSelective(product, example);

        if (product.getIsShow() != null && product.getIsShow() == 1) {
            //将商品的id发送给ActiveMQ
            // 采用消息服务模式
            // 将商品信息添加到solr服务器中（发送消息（ids）到ActiveMQ中）

            jmsTemplate.send("productIds", new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    //创建消息
                    //使用session创建文本消息
                    TextMessage textMessage = session.createTextMessage(ids);

                    return textMessage;
                }
            });

        }


    }


    @Override
    public Product findProductById(Long id) {

        if (id != null) {
            Product product = productMapper.selectByPrimaryKey(id);
            return product;
        }
        return null;
    }

    @Override
    public List<SuperPojo> findByProductId(Long productId) {
        //根据商品的id查询库存的信息
        List<SuperPojo> superPojoList = skuMapper.findSkuByProductId(productId);
        return superPojoList;
    }
}
